<template>
  <view class="">
    <van-uploader
      :before-read="beforeRead"
      :after-read="afterRead"
      :multiple="multiple"
      :accept="accept"
      :max-count="limt"
    >
      <van-button icon="plus" type="primary">上传文件</van-button>
    </van-uploader>
    <!-- 上传的列表 -->
    <view class="file_container">
      <view class="file_item" v-for="(item, index) in fileList" :key="index">
        <view class="file_item_content">
          {{ item.name }}
        </view>
        <van-icon name="close" @click="handleClose(index)" />
      </view>
    </view>
  </view>
</template>

<script lang="ts" setup>
const props = defineProps({
  multiple: {
    type: Boolean,
    default: false,
  },
  fileSize: {
    type: Number,
    default: 5,
  },
  limt: {
    type: Number,
    default: 1,
  },
  accept: {
    type: String,
    default: "image/jpg, image/png, .docx, .doc, .xls, .xlsx",
  },
});
const { multiple, limt, accept, fileSize } = toRefs(props);
const fileList = ref([
  // { url: 'https://fastly.jsdelivr.net/npm/@vant/assets/leaf.jpeg' },
]);

// 在前置钩子中完成图片压缩功能
function beforeRead(file) {
  // 校验文件数量
  if (fileList.value.length >= limt.value) {
    uni.showToast({
      title: `上传文件数量不能超过 ${limt.value} 个!`,
      icon: "none",
    });
    return false;
  }
  // 校验重复文件
  const isRepeat = fileList.value.some((item) => item.name === file.name);
  if (isRepeat) {
    uni.showToast({
      title: "文件重复",
      icon: "none",
    });
    return false;
  }
  // 校检文件大小
  if (fileSize.value) {
    const isLt = file.size / 1024 / 1024 < fileSize.value;
    if (!isLt) {
      uni.showToast({
        title: `上传文件大小不能超过 ${fileSize.value} MB!`,
        icon: "none",
      });
      return false;
    }
  }
  return true;
}

function afterRead(file) {
  // 此时可以自行将文件上传至服务器
  console.log("文件上传:", file);
  // 将文件添加到列表中
  fileList.value.push({
    url: file.content,
    name: file.file.name,
  });
}

/*
 * 关闭按钮
 */
function handleClose(index) {
  console.log("关闭的按钮：", index);
  fileList.value.splice(index, 1);
}
</script>

<style lang="scss" scoped>
.file_container {
  width: 100%;
  margin-top: 6px;
  .file_item {
    width: 100%;
    margin-bottom: 6px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    border: 1px solid #e5e5e5;
    border-radius: 4px;
    padding: 5px 10px;
    .file_item_content {
      font-size: 15px;
      color: #333;
      width: 90%;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }
    .van-icon-close {
      color: #f00;
    }
  }
}
</style>